import _ from 'underscore';
import BaseModel from "../../base/models/BaseModel.js";
import { getTvaPart, strToFloat } from '../../math.js';
import Radio from 'backbone.radio';


const ExpenseHtModel = BaseModel.extend({
    props: [
        'id',
        'expenses_ht',
    ],
    validation: {
        expenses_ht: {
            required: false,
            pattern: 'amount',
            msg: "Le montant doit être un nombre",
        },
    },
    initialize: function(){
        ExpenseHtModel.__super__.initialize.apply(this, arguments);
        var channel = this.channel = Radio.channel('facade');
        this.on('saved', function(){channel.trigger('changed:discount')});
    },
    ht: function(){
        return strToFloat(this.get('expenses_ht'));
    },
    tva_key: function(){
        var config_channel = Radio.channel('config');
        this.tva_options = config_channel.request('get:options', 'tvas');
        var result
        var tva_object = _.find(
            this.tva_options,
            function(val){return val['default'];}
        );
        if (_.isUndefined(tva_object)){
            result = 0;
        } else {
            result = strToFloat(tva_object.value);
        }
        if (result < 0){
            result = 0;
        }
        return result;
    },
    tva_amount: function(){
        return getTvaPart(this.ht(), this.tva_key());
    },
    tvaParts: function(){
        var result = {};
        var tva_key = this.tva_key();
        var tva_amount = this.tva_amount();
        if (tva_amount == 0){
            return result;
        }
        result[tva_key] = tva_amount;
        return result;
    },
    ttc: function(){
        return this.ht() + this.tva_amount();
    }
});
export default ExpenseHtModel;
